package com.hfjyz.registration.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.hfjyz.registration.command.OrderInfoPayCommand;
import com.hfjyz.registration.contants.ExamContants;
import com.hfjyz.registration.model.Exam;
import com.hfjyz.registration.service.OrderInfoService;

public class OrderInfoPaySearchController extends SimpleFormController {
	private OrderInfoService orderInfoService;

	public OrderInfoService getOrderInfoService() {
		return orderInfoService;
	}

	public void setOrderInfoService(OrderInfoService orderInfoService) {
		this.orderInfoService = orderInfoService;
	}

	@SuppressWarnings("rawtypes")
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		OrderInfoPayCommand cmd = (OrderInfoPayCommand) command;
		Exam exam = (Exam) request.getSession().getAttribute(
				ExamContants.SESSION_KEY_EXAM_INFO);
		cmd.setExam(exam);
		Date now = Calendar.getInstance().getTime();
		if (exam.getPayStartDate() == null || now.before(exam.getPayStartDate())) {
			throw new Exception("尚未到支付时间，请等待！");
		} else if (now.after(exam.getPayEndDate())) {
			throw new Exception("很抱歉，支付已经结束！");
		}
		String userId = request.getParameter("userId");
		cmd.setUserId(Integer.valueOf(userId));
		return null;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		OrderInfoPayCommand cmd = (OrderInfoPayCommand) command;
		Exam exam = (Exam) request.getSession().getAttribute(
				ExamContants.SESSION_KEY_EXAM_INFO);
		cmd.setExam(exam);
		orderInfoService.payGoing(cmd, errors);
		return new ModelAndView(getFormView());
	}
}
